package com.aliyun.messagemgt.util;

import com.aliyun.messagemgt.common.constant.CommonConstant;
import com.aliyun.messagemgt.common.constant.DingConstant;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

public class DingRobotSignUtil {

    private static Logger logger = LoggerFactory.getLogger(DingRobotSignUtil.class);

    public static String getDingRobotSign(String secret, long timestamp) {
        String encode = null;
        try {
            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance(DingConstant.HMACSHA256);
            mac.init(new SecretKeySpec(secret.getBytes(CommonConstant.UTF_8), DingConstant.HMACSHA256));
            byte[] signData = mac.doFinal(stringToSign.getBytes(CommonConstant.UTF_8));
            encode = URLEncoder.encode(new String(Base64.encodeBase64(signData)), CommonConstant.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("钉钉机器人获取签名sign出现错误 {}", e.toString());
        }
        return encode;
    }
}
